<template>

    <el-cascader
      :value="regionArray"
      @active-item-change="regionItemChangeHandle"
      @change="regionChangeHandle"
      :options="regionOptions"
      :props="props"
      :key="refreshItem"
      clearable
      filterable></el-cascader>

</template>

<script>
  import { selectRegion } from "@/api/system/region";
  import {regeion_parent_code} from '@/utils/constant'
  export default {
    name: 'RegionSelect',
    props: {
      codes: {
        type: [Array, String],
        default: function () {
          return []
        }
      },
      queryParams: {
        parentCode: null,
        name: null
      },
      props: {
        type: Object,
        default: function () {
          return {
            value: 'areaCode',
            label: 'name',
            children: 'children'
          }
        }
      },
      outPut: {
        type: String,
        default: 'string'   // 可以选择string, array
      },
      maxLength: {
        type: Number,
        default: 2
      },
      level: {
        type: Number,
        default: 1
      },
      parentCode: {
        type: String,
        default: regeion_parent_code
      },
      refreshItem: {
        type: Number,
        default: 0
      },
    },
    data () {
      return {
        regionOptions: []
      }
    },
    computed: {
      regionArray () {
        let regions = []
        //console.log(this.codes)
        if (Object.prototype.toString.apply(this.codes) === '[object Array]') {
          regions = this.codes
        } else if (Object.prototype.toString.apply(this.codes) === '[object String]' && this.codes.length > 0) {
          let regionsTemp = this.codes.split('-')
          regionsTemp.forEach(function (data, index, arr) {
            regions.push(+data)
          })
        }
        //console.log("regions"+regions);
        return regions
      }
    },
    watch: {
      codes: function (newval, oldVal) {
        //console.log('new: %s, old: %s', newval, oldVal)
        this.defaultRegionHandle()
      }
    },
    mounted () {
      this.listProv()
    },
    created() {

    },
    methods: {
      regions () {
        let regions = []
        if(!this.codes) {
          return regions;
        }

        if (Object.prototype.toString.apply(this.codes) === '[object Array]') {
          regions = this.codes
        } else if (Object.prototype.toString.apply(this.codes) === '[object String]' && this.codes.length > 0) {
          let regionsTemp = this.codes.split('-')
          regionsTemp.forEach(function (data, index, arr) {
            regions.push(+data)
          })
        }
        return regions
      },
      listProv () {
        let queryParams = {};
        queryParams['parentCode'] = this.parentCode;
        queryParams['level'] = this.level;
        selectRegion(queryParams).then(res => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.regionOptions = res.data
          for (let item of this.regionOptions) {
            this.$set(item, 'children', [])
          }
          this.defaultRegionHandle()
        });

      },
      regionItemChangeHandle (val) {
        let region = this.getCascaderItm(val, this.regionOptions)
        // 已经获取过不重复获取
        if (region[region.length - 1].children.length > 0 ) {
          return
        }
        let queryParams = {};
        queryParams['parentCode'] = region[region.length - 1].areaCode

        selectRegion(queryParams).then(res => {
          this.loading = false
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          // 最多四层结构
          if (region.length < this.maxLength) {
            for (let i of res.data) {
              this.$set(i, 'children', [])
            }
          }
          this.$set(region[region.length - 1], 'children', res.data)
        });
      },
      // 获取级联选择器的值
      getCascaderItm (valArr, regionOptions) {
        //if(!valArr.length > 0) return null;
        //console.log("regionOptions===")
        //console.log(regionOptions)
        return valArr.map(function (value, index, array) {
          for (var itm of regionOptions) {
            if (itm.areaCode === value) {
              regionOptions = itm.children
              return itm
            }
          }
          return null
        })
      },
      // 设置初始值
      defaultRegionHandle () {
        if(!this.regions() || !this.regions().length > 0) {
          return ;
        }
        if (this.regions().length > 0) {
          this.listDefaultRegionHandle(this.regions(), 0)
        }
      },
      listDefaultRegionHandle (val, ind) {
        let region = this.getCascaderItm(val, this.regionOptions)

        // 因为已经定位三层结构，所以最后一层不为null，即不重复查询
        // 已经获取过，不重复获取
        if (region[region.length - 1]) {
          return
        }
        let queryParams = {};
        queryParams['parentCode'] = region[ind].areaCode

        selectRegion(queryParams).then(res => {
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          if (ind < 1 && region.length < this.maxLength) {
            for (let item of res.data) {
              this.$set(item, 'children', [])
            }
          }
          this.$set(region[ind], 'children', res.data)
          if (ind < 1) {
            this.listDefaultRegionHandle(val, 1)
          }
        });
      },
      regionChangeHandle (valArr) {
        this.submitModifyHandle(valArr)
      },
      // 向父组件提交修改信息，触发父组件方法
      submitModifyHandle (valArr) {
        //console.log(valArr)
        this.$nextTick(() => {
          let region = this.getCascaderItm(valArr, this.regionOptions)
          let nmArr = []
          let areaCodeArr = []
          region.forEach(function (data, index, arr) {
            nmArr.push(data.name)
            areaCodeArr.push(data.areaCode)
          })
          if (this.outPut === 'string') {
            this.$emit('modify', valArr.join('-'), nmArr.join('-'), areaCodeArr.join('-'),)
          } else {
            this.$emit('modify', valArr, nmArr,areaCodeArr)
          }
        })
      }
    }
  }
</script>
